package org.jeecg.modules.system.service.impl;

import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.YouBianCodeUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysCategory;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.mapper.SysCategoryMapper;
import org.jeecg.modules.system.model.SysCategoryTreeModel;
import org.jeecg.modules.system.model.SysDepartTreeModel;
import org.jeecg.modules.system.model.TreeSelectModel;
import org.jeecg.modules.system.service.ISysCategoryService;
import org.jeecg.modules.system.util.FindsCategoryChildrenUtil;
import org.jeecg.modules.system.util.FindsDepartsChildrenUtil;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * @Description: 分类字典
 * @Author: jeecg-boot
 * @Date: 2019-05-29
 * @Version: V1.0
 */
@Service
public class SysCategoryServiceImpl extends ServiceImpl<SysCategoryMapper, SysCategory> implements ISysCategoryService {

    @Override
    public void addSysCategory(SysCategory sysCategory) {
        String categoryCode = "";
        String categoryPid = ISysCategoryService.ROOT_PID_VALUE;
        String parentCode = null;
        if (oConvertUtils.isNotEmpty(sysCategory.getPid())) {
            categoryPid = sysCategory.getPid();

            //PID 不是根节点 说明需要设置父节点 hasChild 为1
            if (!ISysCategoryService.ROOT_PID_VALUE.equals(categoryPid)) {
                SysCategory parent = baseMapper.selectById(categoryPid);
                parentCode = parent.getCode();
                if (parent != null && !"1".equals(parent.getHasChild())) {
                    parent.setHasChild("1");
                    baseMapper.updateById(parent);
                }
            }
        }
        //update-begin--Author:baihailong  Date:20191209 for：分类字典编码规则生成器做成公用配置
        JSONObject formData = new JSONObject();
        formData.put("pid", categoryPid);
        categoryCode = (String) FillRuleUtil.executeRule("category_code_rule", formData);
        //update-end--Author:baihailong  Date:20191209 for：分类字典编码规则生成器做成公用配置
        sysCategory.setCode(categoryCode);
        sysCategory.setPid(categoryPid);
        baseMapper.insert(sysCategory);
    }

    @Override
    public void updateSysCategory(SysCategory sysCategory) {
        if (oConvertUtils.isEmpty(sysCategory.getPid())) {
            sysCategory.setPid(ISysCategoryService.ROOT_PID_VALUE);
        } else {
            //如果当前节点父ID不为空 则设置父节点的hasChild 为1
            SysCategory parent = baseMapper.selectById(sysCategory.getPid());
            if (parent != null && !"1".equals(parent.getHasChild())) {
                parent.setHasChild("1");
                baseMapper.updateById(parent);
            }
        }
        baseMapper.updateById(sysCategory);
    }

    @Override
    public List<SysCategoryTreeModel> queryTreeList() {

        LambdaQueryWrapper<SysCategory> query = new LambdaQueryWrapper<SysCategory>();
        query.eq(SysCategory::getStatus, CommonConstant.STATUS.toString());
        query.orderByAsc(SysCategory::getRowIndex);
        List<SysCategory> list = this.list(query);
        System.out.println(list.toString());
        // 调用wrapTreeDataToTreeList方法生成树状数据
        List<SysCategoryTreeModel> listResult = FindsCategoryChildrenUtil.wrapTreeDataToTreeList(list);
        return listResult;
    }

    @Override
    public List<TreeSelectModel> queryListByCode(String pcode) throws JeecgBootException {
        String pid = ROOT_PID_VALUE;
        if (oConvertUtils.isNotEmpty(pcode)) {
            List<SysCategory> list = baseMapper.selectList(new LambdaQueryWrapper<SysCategory>().eq(SysCategory::getCode, pcode));
            System.out.println("-----------------------------------------------" + list.size());
            if (list == null || list.size() == 0) {
                throw new JeecgBootException("该编码【" + pcode + "】不存在，请核实!");
            }
            if (list.size() > 1) {
                throw new JeecgBootException("该编码【" + pcode + "】存在多个，请核实!");
            }
            pid = list.get(0).getId();
        }
        return baseMapper.queryListByPid(pid, null);
    }

    @Override
    public List<TreeSelectModel> queryListByPid(String pid) {
        if (oConvertUtils.isEmpty(pid)) {
            pid = ROOT_PID_VALUE;
        }
        return baseMapper.queryListByPid(pid, null);
    }

    @Override
    public List<TreeSelectModel> queryListByPid(String pid, Map<String, String> condition) {
        if (oConvertUtils.isEmpty(pid)) {
            pid = ROOT_PID_VALUE;
        }
        return baseMapper.queryListByPid(pid, condition);
    }

    @Override
    public String queryIdByCode(String code) {
        return baseMapper.queryIdByCode(code);
    }

    @Override
    public String queryIdByRowIndex(Integer rowIndex, String pid) {
        return baseMapper.queryIdByRowIndex(rowIndex, pid);
    }

    /**
     * 点开目录时添加下标并排序
     */
    @Override
    public List<SysCategory> rowIndex(List<SysCategory> categoryList) {
        if (!categoryList.isEmpty()) {
            SysCategory lastOne = categoryList.get(categoryList.size() - 1);
            for (int i = 0; i < categoryList.size(); i++) {
                // 为没有下标的对象赋值
                if (null == categoryList.get(i).getRowIndex()) {
                    SysCategory sysCategory = categoryList.get(i).setRowIndex(i);
                    updateSysCategory(sysCategory);
                }
            }
            // 新增对象赋值下标
            if (null != lastOne.getRowIndex()) {
                SysCategory sysCategory = categoryList.get(lastOne.getRowIndex()).setRowIndex(categoryList.size() - 1);
                updateSysCategory(sysCategory);
            }
        }

        // 升序排列list
        categoryList.sort((o1, o2) -> {
            return o1.getRowIndex() > o2.getRowIndex() ? 1 : -1;
        });
        return categoryList;
    }
}
